package io.bsly.config.activeMq;

import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.jms.Queue;
import javax.jms.TextMessage;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Component
public class ActiveMqProducer {
    protected Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private JmsTemplate jmsTemplate;

    private static Map<String, Queue> map = new HashMap<String, Queue>();

    public void send(Queue queue, String msg) {
        log.info("发送MQ消息:msg={}", msg);
        this.jmsTemplate.convertAndSend(queue, msg);
    }

    /**
     * 发送延迟消息
     * @param msg
     * @param delay
     */
    public void send(Queue queue, String msg, long delay) {
        log.info("发送MQ延时消息:msg={},delay={}", msg, delay);
        jmsTemplate.send(queue, session -> {
            TextMessage tm = session.createTextMessage(msg);
            tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
            tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 1*1000);
            tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, 1);
            return tm;
        });
    }

    public void send(String queueName, String msg){
        send(getQueue(queueName), msg);
    }

    public void send(String queueName, String msg, long delay){
        send(getQueue(queueName), msg, delay);
    }

    public static Queue getQueue(String queueName){
        Queue queue = map.get(queueName);
        if(queue == null){
            synchronized (ActiveMqProducer.class){
                if (queue == null) {
                    queue = new ActiveMQQueue(queueName);
                    map.put(queueName, queue);
                }
            }
        }
        return queue;
    }
}
